# coding=utf-8
import sys
from function_utils import Global, Common


def crontab_info():
    cmd = 'crontab -l'
    info = Common.execute_cmd(cmd)[1]
    if not info:
        print('No crontab')
    return info


def add_crontab(task):
    cmd = '''
    (crontab -l | grep -v '^#' | grep -v "{0}"; echo "{1}") | crontab -
    '''.format(task.replace('*', '\\*'), task)
    ret, out, err = Common.execute_cmd(cmd)
    print(out)
    print(err)


def del_crontab(task):
    cmd = '''
    (crontab -l | grep -v '^#' | grep -v "{0}") | crontab -
    '''.format(task.replace('*', '\\*'))
    ret, out, err = Common.execute_cmd(cmd)
    print(out)
    print(err)


def write_widgets_value(value):
    data = [
        {},
        {"MultiInfoText": value},
        {},
        {}
    ]
    Global.values_write(data)
    Global.report_info(100)


def main():
    if sys.argv[1] == 'pre':
        write_widgets_value(crontab_info())
    elif sys.argv[1] == 'start':
        data = Global.values_parse(sys.argv[2])
        task = data[3]['Entry'].strip()
        if data[2]['Combobox'].strip() == 'Add':
            add_crontab(task)
        else:
            del_crontab(task)
        write_widgets_value(crontab_info())


if __name__ == '__main__':
    main()

